<template>
    <div>
        <global-tables
            @handleAllSelect="handleAllSelect"
            @changePage="handleChangePage"
            :list="list"
            :total="total"
            :loading="loading"
            :columns="columns"
            :current="search.Page"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <div>
                            <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                                <Icon type="md-add" size="18"/>新建
                            </Button>
                            <Button v-if="isDelete" class="features-btn btn-auto-m" @click="handleBtnClick(null,'delete')">
                                <Icon type="md-trash" size="17"/>删除
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'on')">
                                <Icon type="ios-unlock-outline" size="17"/>启用
                            </Button>
                            <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'off')">
                                <Icon type="ios-lock-outline" size="17"/>停用
                            </Button>
                        </div>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入品牌名称">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle" width="600">
            <div v-if="isModal">
                <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="所属供应商" prop="SupplieerID">
                                <AsyncSelect
                                    :url="'Supplier/GetAllGridJson'"
                                    :value="'SupplieerID'"
                                    :currentModel="formItem.SupplieerID"
                                    @setDictionaries="setDictionaries"
                                ></AsyncSelect>
                            </FormItem>
                        </i-col>
                    </Row>
                    <Row>
                        <i-col :lg="{ span: 12}">
                            <FormItem label="品牌名称" prop="BrandName">
                                <i-input v-model="formItem.BrandName" placeholder="请输入品牌名称"></i-input>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
            </div>
            <div slot="footer">
                <Button size="large" @click="handleClose">取消</Button>
                <Button type="primary" size="large" @click="handleSubmit('formItem')">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
/**
 * 品牌列表
 */
import { cyclicRouting } from '@/util';
import { getModulePermission } from '@/api/user';
import GlobalTables from '@/components/GlobalTables';
import AsyncSelect from '@/components/AsyncSelect';
import Api from './service';

export default {
    name: 'ProductsBrand',
    components: {
        GlobalTables,
        AsyncSelect
    },
    data() {
        const validatorSupplierID = (rule, value, callback) => {
            setTimeout(() => {
                if (this.formItem.SupplierID == '' || !this.formItem.SupplierID) {
                    callback(new Error('请选择所属供应商'));
                } else {
                    callback();
                }
            }, 100);
        };
        return {
            /**
             *  list 表格数据
             *  itemId 对话框id : 修改的时候需要
             *  allSelectArr 多选数据 : 批量删除或者停用
             *  loading 表格加载
             *  total 表格总页
             *  formItem 表单数据 : 提交表单对应的数据
             *  ruleValidate 表单校验
             *  isDelete 删除按钮
             *  isAddBtn 添加按钮
             *  isProhibit 停用按钮
             *  isModal 对话框状态
             *  ModalTitle  对话框标题
             *  search  请求数据 : 分页 模糊搜索
             *  columns 表头
             *  validatorSupplierID 自定义校验
             */
            list: [],
            total: 0,
            itemId: 0,
            loading: true,
            isDelete: false,
            isAddBtn: false,
            isProhibit: false,
            isModal: false,
            allSelectArr: null,
            ModalTitle: '新建品牌',
            formItem: this.initFormItem(),
            search: {
                keyword: '',
                pageindex: 1,
                pagesize: 10
            },
            ruleValidate: {
                SupplierID: [
                    {
                        required: true,
                        validator: validatorSupplierID,
                        message: '请选择所属供应商',
                        trigger: 'change'
                    }
                ],
                BrandName: [
                    {
                        required: true,
                        message: '请输入品牌名称',
                        trigger: 'change'
                    }
                ]
            },
            /* 表头 */
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '品牌编码',
                    key: 'BrandCode'
                },
                {
                    title: '品牌名称',
                    key: 'BrandName'
                },
                {
                    title: '所属供应商',
                    key: 'SupplierName'
                },
                {
                    title: '状态',
                    render: (h, params) => {
                        const { IsActivity } = params.row;
                        if (IsActivity) {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'processing',
                                        text: '正常'
                                    }
                                })
                            ]);
                        } else {
                            return h('div', [
                                h('Badge', {
                                    props: {
                                        status: 'error',
                                        text: '停用'
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: '操作',
                    width: 70,
                    align: 'center',
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                )
                        ]);
                    }
                }
            ]
        };
    },
    methods: {
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 提交 */
        handleSubmit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    let data = this.formItem;
                    Api.addTablesItem(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.isModal = false;
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 供应商选择 */
        setDictionaries(item, value) {
            this.formItem[value] = item.ID + ' ';
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.rows;
                this.loading = false;
                this.total = res.records;
            });
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 对话框 */
        handleBtnClick(item, type) {
            this.ModalTitle = '新建品牌';
            this.formItem = this.initFormItem();
            if (type == 'edit' || type == 'add') {
                this.itemId = 0;
                if (type == 'edit') {
                    this.itemId = item.ID;
                    this.ModalTitle = '修改品牌';
                    Api.getItemInfo({
                        keyValue: item.ID
                    }).then(res => {
                        this.isModal = true;
                        this.formItem = {
                            ...res.data,
                            SupplieerID: res.data.SupplieerID + ''
                        };
                    });
                } else {
                    this.isModal = true;
                }
            } else if (type === 'off' || type === 'on') {
                let title = '';
                if (type == 'off') {
                    title = '停用';
                } else {
                    title = '启用';
                }
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要${title}吗`,
                        onOk: () => {
                            Api.setDisableEnable({
                                keyValue: this.allSelectArr,
                                value: type == 'off' ? 0 : 1
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请先选择需要操作的记录');
                }
            } else if (type === 'delete') {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要删除吗`,
                        onOk: () => {
                            Api.deleteItem({
                                keyValue: this.allSelectArr
                            }).then(res => {
                                if (res.state == 'success') {
                                    this.$Message.success(res.message);
                                    this.allSelectArr = '';
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('取消成功');
                        }
                    });
                } else {
                    this.$Message.error('请先选择需要操作的记录');
                }
            }
        },
        /* 表单数据 */
        initFormItem() {
            return {
                SupplieerID: '',
                BrandName: ''
            };
        },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesizeize = page;
                this.getTablesListData();
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        }
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'delete') {
                        this.isDelete = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    } else if (res.data[item].name == 'onoff') {
                        this.isProhibit = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    }
};
</script>

<style>
</style>
